import {
	Button,
	Card,
	Form,
	Input,
	Modal,
	Select,
	Space,
	Table,
	Tag,
	message,
} from "antd";
import { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { commonService } from "@/api/services/commonService";
import { Iconify } from "@/components/icon";
import { UploadBox } from "@/components/upload";

interface AttachmentItem {
	id: number;
	category: {
		id: number;
		name: string;
	};
	url: string;
	name: string;
	filesize: number;
	mimetype: string;
	createtime: number;
	fullurl: string;
}

interface CategoryItem {
	id: number;
	name: string;
}

interface UploadFormData {
	file: string;
	name: string;
	category_id?: number;
}

const getFileTypeFromUrl = (url: string) => {
	const extension = url.split(".").pop()?.toLowerCase();
	switch (extension) {
		case "jpg":
		case "jpeg":
		case "png":
		case "gif":
		case "webp":
			return "image/" + extension;
		case "mp4":
		case "webm":
			return "video/" + extension;
		case "mp3":
		case "wav":
			return "audio/" + extension;
		case "pdf":
			return "application/pdf";
		case "doc":
		case "docx":
			return "application/msword";
		case "xls":
		case "xlsx":
			return "application/excel";
		case "zip":
		case "rar":
			return "application/" + extension;
		case "txt":
			return "text/plain";
		default:
			return "application/octet-stream";
	}
};

const getFileIcon = (mimetype: string) => {
	if (mimetype.startsWith("image/")) {
		return "eva:image-fill";
	}
	if (mimetype.startsWith("video/")) {
		return "eva:video-fill";
	}
	if (mimetype.startsWith("audio/")) {
		return "eva:music-fill";
	}
	if (mimetype === "application/pdf") {
		return "eva:file-text-fill";
	}
	if (mimetype === "application/msword") {
		return "eva:file-text-fill";
	}
	if (mimetype === "application/excel") {
		return "eva:file-text-fill";
	}
	if (mimetype.includes("zip") || mimetype.includes("rar")) {
		return "eva:archive-fill";
	}
	if (mimetype === "text/plain") {
		return "eva:file-text-fill";
	}
	return "eva:file-fill";
};

export default function AttachmentPage() {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<AttachmentItem[]>([]);
	const [total, setTotal] = useState(0);
	const [current, setCurrent] = useState(1);
	const [uploadVisible, setUploadVisible] = useState(false);
	const [uploadForm] = Form.useForm<UploadFormData>();
	const [categories, setCategories] = useState<CategoryItem[]>([]);

	const loadData = async (page = 1) => {
		try {
			setLoading(true);
			const response = await commonService.getAttachmentList({
				page,
				limit: 10,
			});
			setData(response.items);
			setTotal(response.total);
		} catch (error) {
			message.error("加载失败");
		} finally {
			setLoading(false);
		}
	};

	const loadCategories = async () => {
		try {
			const items = await commonService.getCategoryList();
			setCategories(items);
		} catch (error) {
			message.error("加载分类失败");
		}
	};

	const handlePageChange = (page: number) => {
		setCurrent(page);
		loadData(page);
	};

	const handleUpload = async (values: UploadFormData) => {
		try {
			await commonService.saveAttachment({
				name: values.name,
				url: values.file,
				category_id: values.category_id,
			});
			message.success("上传成功");
			setUploadVisible(false);
			uploadForm.resetFields();
			loadData();
		} catch (error) {
			message.error("上传失败");
		}
	};

	const handleDelete = async (id: number) => {
		try {
			await commonService.deleteAttachment(id);
			message.success("删除成功");
			loadData(current);
		} catch (error) {
			message.error("删除失败");
		}
	};

	const columns: ColumnsType<AttachmentItem> = [
		{
			title: "预览",
			dataIndex: "fullurl",
			width: 100,
			render: (url) => {
				const mimetype = getFileTypeFromUrl(url);
				const isImage = mimetype.startsWith("image/");

				return (
					<div
						style={{
							width: "50px",
							height: "50px",
							display: "flex",
							alignItems: "center",
							justifyContent: "center",
							background: "#f5f5f5",
							borderRadius: "4px",
						}}
					>
						{isImage ? (
							<img
								src={url}
								alt=""
								style={{
									width: "100%",
									height: "100%",
									objectFit: "cover",
									borderRadius: "4px",
								}}
							/>
						) : (
							<Iconify icon={getFileIcon(mimetype)} size={24} />
						)}
					</div>
				);
			},
		},
		{
			title: "文件名",
			dataIndex: "name",
		},
		{
			title: "分类",
			dataIndex: "category",
			render: (category) => (
				<Tag color={category ? "blue" : "default"}>
					{category ? category.name : "未分类"}
				</Tag>
			),
		},
		{
			title: "大小",
			dataIndex: "filesize",
			render: (size) => `${(size / 1024).toFixed(2)} KB`,
		},

		{
			title: "上传时间",
			dataIndex: "createtime",
			render: (time) => dayjs.unix(time).format("YYYY-MM-DD HH:mm:ss"),
		},
		{
			title: "操作",
			key: "action",
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => window.open(record.fullurl)}>
						查看
					</Button>
					<Button
						type="link"
						danger
						onClick={() =>
							Modal.confirm({
								title: "确认删除",
								content: "确定要删除该附件吗？",
								onOk: () => handleDelete(record.id),
							})
						}
					>
						删除
					</Button>
				</Space>
			),
		},
	];

	useEffect(() => {
		loadData();
		loadCategories();
	}, []);

	return (
		<>
			<Card
				title="附件管理"
				extra={
					<Button type="primary" onClick={() => setUploadVisible(true)}>
						上传附件
					</Button>
				}
			>
				<Table
					columns={columns}
					dataSource={data}
					rowKey="id"
					loading={loading}
					pagination={{
						total,
						current,
						onChange: handlePageChange,
					}}
				/>
			</Card>

			<Modal
				title="上传附件"
				open={uploadVisible}
				onCancel={() => {
					setUploadVisible(false);
					uploadForm.resetFields();
				}}
				footer={null}
			>
				<Form
					form={uploadForm}
					onFinish={handleUpload}
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 20 }}
				>
					<Form.Item
						label="附件"
						name="file"
						rules={[{ required: true, message: "请上传附件" }]}
					>
						<UploadBox />
					</Form.Item>
					<Form.Item
						label="名称"
						name="name"
						rules={[{ required: true, message: "请输入附件名称" }]}
					>
						<Input placeholder="请输入附件名称" />
					</Form.Item>
					<Form.Item label="分类" name="category_id">
						<Select
							placeholder="请选择分类"
							allowClear
							options={categories.map((item) => ({
								label: item.name,
								value: item.id,
							}))}
						/>
					</Form.Item>
					<Form.Item wrapperCol={{ offset: 4, span: 20 }}>
						<Space>
							<Button type="primary" htmlType="submit">
								确定
							</Button>
							<Button
								onClick={() => {
									setUploadVisible(false);
									uploadForm.resetFields();
								}}
							>
								取消
							</Button>
						</Space>
					</Form.Item>
				</Form>
			</Modal>
		</>
	);
}
